package com.app.util;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpSession;

/**
 * token获取,校验
 * TODO
 * @author zoe
 * 2016年4月12日
 */
public class TokenUtil {

	public static final String TOKEN_STRING_NAME = "tokenCode";

	/**
	 * 保存到session中
	 * @param tokenStr
	 * @param httpSession
	 */
	private static void saveTokenString(String tokenStr,HttpSession httpSession) {
		Map<String,String> map = new HashMap<String,String>();
		map.put(tokenStr, tokenStr);
		httpSession.setAttribute(TOKEN_STRING_NAME, map);
	}

	/**
	 * 生成tokenStr
	 * @return
	 */
	private static String generateTokenString() {

		return new Long(System.currentTimeMillis()).toString();

	}

	/**
	 * 获取tokenStr
	 * @param httpSession
	 * @return
	 */
	public static String getTokenString(HttpSession httpSession) {

		String tokenStr = generateTokenString();

		saveTokenString(tokenStr,httpSession);

		return tokenStr;

	}

	/**
	 * 验证
	 * @param tokenStr
	 * @param httpSession
	 * @return
	 */
	public static boolean isTokenStringValid(String tokenStr,HttpSession httpSession) {
		@SuppressWarnings("unchecked")
		Map<String,String> map = (Map<String,String>)httpSession.getAttribute(TOKEN_STRING_NAME);
		if(map.containsKey(tokenStr)){
			map.remove(tokenStr);
			return true;
		}

		return false;

	}

}